//
//  BPHomeViewController.m
//  BeautyPicture
//
//  Created by 沈振邦 on 15/7/27.
//  Copyright (c) 2015年 szb. All rights reserved.
//

#import "BPHomeViewController.h"
#import "PersonalCenterVC.h"
#import "BPProductModeViewController.h"
#import "printViewController.h"
#import "BPProductTool.h"
#import "HomeModel.h"
#import "PersonCenterGroup.h"
#import "PersonCenterCellView.h"
#import "PCArrowItm.h"
#import "BPLoginViewController.h"
#import "AccountTool.h"
#import "BaseWebViewController.h"
#import "yunChunVCViewController.h"
#import "adviceVC.h"
#import "filmViewController.h"
#import "BPhttpTool.h"
#import "BPImageTool.h"
#import "payView.h"
#import "inviteVC.h"
#import "setupViewController.h"
#import "kefuVC.h"
#import "homeCell.h"
#import "productCenterVC.h"
#import "orderCenterVC.h"
#import "MeiYinBiViewC.h"
#import "PayOverSuccessViewController.h"



#define HMAccountFilepath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"account.data"]

@interface BPHomeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic,assign)BOOL isOpen;

@property (nonatomic,strong)NSMutableArray *btnDataArry;

@property (nonatomic,strong)UIButton *loginBtn;

@property (nonatomic, strong) UIView *viewAll;

@end

@implementation BPHomeViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    [self loginTitle];
    [self judgeIsAccount];
}

- (void)loginTitle {
    
    if ([AccountTool account].uid == nil) {
        [_loginBtn setTitle:@"登陆" forState:(UIControlStateNormal)];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化数据
    [self setUpBaseData];
    //初始化UI主控件
    [self drawUIView];
}

- (void)setUpBaseData
{
    //初始化
    _dataManger = [[CoreDateManager alloc] init];
    //从数据库中获取显示缓存数据
    _btnDataArry = [_dataManger homeData];
    //数据下载
    [self downLoadData];
}

- (void)downLoadData
{
    //获取按钮的图片和文字
    [BPProductTool homeDatasuccess:^(id result) {
        _btnDataArry = result;
        [_homeCollection reloadData];
        //数据库更新
        [_dataManger deleteData];
        [_dataManger insertCoreData:result];
        
    } failure:^(NSError *error) {
        BPLog(@"网络错误");
    }];
    
    //获取首页头部照片
    [BPhttpTool get:[NSString stringWithFormat:@"%@appapi/getslide/place/1",BPhttp] params:nil success:^(id responseObj) {
        NSArray *arry = responseObj;
        NSDictionary *dic = arry[0];
        NSString *imageUrl = dic[@"icon"];
        [BPImageTool setUpHDImageView:_topBgImage addNsstringUrl:imageUrl];
        [[NSUserDefaults standardUserDefaults] setValue:imageUrl forKey:@"homeTopImage"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    } failure:^(NSError *error) {
        BPLog(@"%@",error);
    }];
}

- (void)drawUIView
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    //设置按钮显示区域（collection）
    _homeID = @"homeID";
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat centerViewY = CGRectGetMaxY(_headView.frame);
    _homeCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0.f, centerViewY - 10.0f, BPScreenW, BPScreenH - centerViewY) collectionViewLayout:layout];
    _homeCollection.delegate = self;
    _homeCollection.dataSource = self;
    //改变按钮区域背景
    _homeCollection.backgroundColor = [UIColor whiteColor];
    [_homeCollection registerClass:[homeCell class] forCellWithReuseIdentifier:_homeID];
    [self.view addSubview:_homeCollection];
    
    
    [self.view addSubview:self.headView];
    [self.view addSubview:self.leftSideView];
    
    
    
    //添加手势
    UISwipeGestureRecognizer *leftSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(dismissMenu)];
    leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:leftSwipeGestureRecognizer];
    
    UISwipeGestureRecognizer *rightSwipeGestureRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(showMenu)];
    rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:rightSwipeGestureRecognizer];
    
    UITapGestureRecognizer *backHome = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissMenu)];
    [self.centerView addGestureRecognizer:backHome];
}

#pragma - mark 设置头部视图，包括侧栏按钮、背景和icon
- (UIView *)headView
{
    if (!_headView) {
        CGFloat bgImageViewWidth = 0.345 * BPScreenH;
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, BPScreenW, bgImageViewWidth - 30)];
        _topBgImage = [[UIImageView alloc] initWithFrame:_headView.bounds];
        _topBgImage.contentMode = UIViewContentModeScaleToFill;
        NSString *imageUrl = [[NSUserDefaults standardUserDefaults] valueForKey:@"homeTopImage"];
        [_headView addSubview:_topBgImage];
        
        if (imageUrl) {
            [BPImageTool setUpHDImageView:_topBgImage addNsstringUrl:imageUrl];
        }else{
            _topBgImage.image = [UIImage imageNamed:@"detail_01"];
        }
        //设置侧边按钮
        _sideNavButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _sideNavButton.frame = CGRectMake(10, 20, 50, 50);
        _sideNavButton.contentMode = UIViewContentModeScaleAspectFit;
        [_sideNavButton setImage:[UIImage imageNamed:@"topleftBtn"] forState:UIControlStateNormal];
        [_headView addSubview:_sideNavButton];
        [_sideNavButton addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchUpInside];
        
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissMenu)];
        [_headView addGestureRecognizer:singleTap];
    }
    return _headView;
}

#pragma mark - 设置左侧导航栏的视图
- (UIView *)leftSideView
{
    if (!_leftSideView) {
        //左侧边栏视图
        CGFloat leftSideX = -220.0f;
        CGFloat leftSideY = 0.f;
        CGFloat leftSideW = 220.0;
        CGFloat leftSideH = self.view.height;
        _leftSideView = [[UIView alloc] initWithFrame:CGRectMake(leftSideX, leftSideY, leftSideW, leftSideH)];
        
        
        self.tableView.frame = _leftSideView.bounds;
        self.tableView.backgroundColor = [UIColor whiteColor];
        [_leftSideView addSubview:self.tableView];
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
        //设置侧边栏头部的ui
        self.tableView.tableHeaderView = [self setUpleftTopView];
        //设置底部的登录、注销按钮
        self.tableView.tableFooterView = [self setUpLeftBottomView];
        
        PersonCenterGroup *group = [PersonCenterGroup group];
        [self.groups addObject:group];
        
        //已经封装好的自定义cell，第一个地方填名称，第二个元素填要放的照片
        PCArrowItm *personCenter = [PCArrowItm itemWithTitle:@"首页" icon:@"homeLeft01"];
        //这是点击该cell以后所做的操作，操作写早block中
        personCenter.operation = ^(){
//            PayOverSuccessViewController *pay = [[PayOverSuccessViewController alloc] init];
//            [self.navigationController pushViewController:pay animated:YES];
//            [self chooseLoginViewController:@"PersonalCenterVC" title:@"个人中心"];
            
            [self dismissMenu];
        };
        
        PCArrowItm *HSquan = [PCArrowItm itemWithTitle:@"我的作品" icon:@"homeLeft03"];
        HSquan.operation = ^(){
            
            if ([AccountTool account].uid == nil) {
                BPLoginViewController *login = [[BPLoginViewController alloc] init];
                login.block = ^{
                    
                };
                [self.navigationController pushViewController:login animated:YES];
            }
            else{
                
                productCenterVC *productCenter = [[productCenterVC alloc] init];
                productCenter.title = @"我的作品";
                [self.navigationController pushViewController:productCenter animated:YES];
            }

//            filmViewController *webVC = [[filmViewController alloc] init];
//            webVC.webName = @"goodCamera.html";
//            webVC.title = @"好摄圈";
//            [self.navigationController pushViewController:webVC animated:YES];
        };
        
        PCArrowItm *yunChun = [PCArrowItm itemWithTitle:@"我的订单" icon:@"homeLeft04"];
        yunChun.operation = ^(){
           
            if ([AccountTool account].uid == nil) {
                BPLoginViewController *login = [[BPLoginViewController alloc] init];
                login.block = ^{
                    
                };
                [self.navigationController pushViewController:login animated:YES];
            }
            else{
                orderCenterVC *orderCenter = [[orderCenterVC alloc] init];
                orderCenter.title = @"我的订单";
                [self.navigationController pushViewController:orderCenter animated:YES];
            }
            
            //[self chooseLoginWebController:@"yunChunVCViewController" title:@"云存储" withWebName:@"cloudSave0.html"];
        };
        
        PCArrowItm *meiYinBi = [PCArrowItm itemWithTitle:@"美印币" icon:@"homeLeft05"];
        meiYinBi.operation = ^(){
//            [self chooseLoginWebController:@"BaseWebViewController" title:@"美印币" withWebName:@"meiyinbi.html"];
            if ([AccountTool account].uid == nil) {
                BPLoginViewController *login = [[BPLoginViewController alloc] init];
                login.block = ^{
                    
                };
                [self.navigationController pushViewController:login animated:YES];
            }
            else{
                
                MeiYinBiViewC *meiyin = [[MeiYinBiViewC alloc] init];
                [self.navigationController pushViewController:meiyin animated:YES];
            }
            
            
        };
        
        PCArrowItm *yaoQing = [PCArrowItm itemWithTitle:@"邀请有奖" icon:@"homeLeft06"];
        yaoQing.operation = ^(){
//            [self chooseLoginWebController:@"inviteVC" title:@"邀请" withWebName:@"invite2.html"];
            if ([AccountTool account].uid == nil) {
                BPLoginViewController *login = [[BPLoginViewController alloc] init];
                login.block = ^{
                    
                };
                [self.navigationController pushViewController:login animated:YES];
            }
            else{
                
                inviteVC *invit = [[inviteVC alloc] init];
                [self.navigationController pushViewController:invit animated:YES];
            }
        };
        
        PCArrowItm *keFu = [PCArrowItm itemWithTitle:@"联系我们" icon:@"homeLeft07"];
        keFu.operation = ^(){
            kefuVC *webVC = [[kefuVC alloc] init];
//            webVC.webName = @"serviceCenter.html";
//            webVC.title = @"客服";
            [self.navigationController pushViewController:webVC animated:YES];
        };
        
        PCArrowItm *sheZhi = [PCArrowItm itemWithTitle:@"设置" icon:@"homeLeft09"];
        sheZhi.operation = ^(){
            
            setupViewController *webVC = [[setupViewController alloc] init];
            [self.navigationController pushViewController:webVC animated:YES];
        };
        //添加自定义的cell
        group.items = @[personCenter,HSquan,yunChun,meiYinBi,yaoQing,keFu,sheZhi];
    }
    return _leftSideView;
}

- (UIView *)setUpLeftBottomView
{
    UIView *leftBottomView = [[UIView alloc] init];
    leftBottomView.size = CGSizeMake(220, 30);
    
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginBtn.frame = CGRectMake(20, 0, 180, 30);
    [self judgeIsAccount];
    _loginBtn.backgroundColor = BPGlobaThemeColor;
    [_loginBtn.layer setCornerRadius:_loginBtn.height / 2.0];
    [leftBottomView addSubview:_loginBtn];
    
    return leftBottomView;
}
- (void)judgeIsAccount
{
    if ([AccountTool account].uid == nil) {
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        
    }else{
        [_loginBtn setTitle:@"注销" forState:UIControlStateNormal];
        
    }
    
    [_loginBtn addTarget:self action:@selector(loginButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)loginButtonAction:(UIButton *)sender {
    
    BPLoginViewController *login  = [[BPLoginViewController alloc]init];
    login.isHome = YES;
    login.block = ^{
        
    };
    if ([_loginBtn.currentTitle isEqualToString:@"登陆"]) {
        
        NSLog(@"第一步");
        [_loginBtn setTitle:@"注销" forState:UIControlStateNormal];
        
        
    } else {
        
        [AccountTool account].uid = nil;
        NSFileManager *defaultManager = [NSFileManager defaultManager];
        if ([defaultManager isDeletableFileAtPath:HMAccountFilepath]) {
            [defaultManager removeItemAtPath:HMAccountFilepath error:nil];
            NSLog(@"注销后的uid = %@", [AccountTool account].uid);
            [_loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
            
        }
    }
    [self.navigationController pushViewController:login animated:YES];
    
}



//- (void)judgeIsAccount
//{
//    if ([AccountTool account].uid == nil) {
//        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
//        [_loginBtn addTarget:self action:@selector(LoginIn) forControlEvents:UIControlEventTouchUpInside];
//    }else{
//        [_loginBtn setTitle:@"注销" forState:UIControlStateNormal];
//        [_loginBtn addTarget:self action:@selector(zhuxiao) forControlEvents:UIControlEventTouchUpInside];
//    }
//}
//
//- (void)LoginIn
//{
//    BPLoginViewController *login = [[BPLoginViewController alloc] init];
//    login.isHome = YES;
//    login.block = ^(){
////        [self judgeIsAccount];
//        [_loginBtn setTitle:@"注销" forState:UIControlStateNormal];
//        [_loginBtn addTarget:self action:@selector(zhuxiao) forControlEvents:UIControlEventTouchUpInside];
//    };
//    [self.navigationController pushViewController:login animated:YES];
//    
//}
//
//- (void)zhuxiao
//{
//    
//    [AccountTool account].uid = nil;
//    //[self judgeIsAccount];
//    NSLog(@"注销后的uid = %@", [AccountTool account].uid);
//   // [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
//    [_loginBtn addTarget:self action:@selector(LoginIn) forControlEvents:UIControlEventTouchUpInside];
//   
//    
//    NSFileManager *defaultManager = [NSFileManager defaultManager];
//    if ([defaultManager isDeletableFileAtPath:HMAccountFilepath]) {
//        [defaultManager removeItemAtPath:HMAccountFilepath error:nil];
//        [self.navigationController popToRootViewControllerAnimated:YES];
//    }
//}

//侧栏头部view
- (UIView *)setUpleftTopView
{
    UIView *leftTopView = [[UIView alloc] init];
    leftTopView.size = CGSizeMake(220, 145.0);
    leftTopView.backgroundColor = [UIColor whiteColor];
    //leftTopView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"homeLeftTopImage"]];
    
    UIImageView *homeicon = [[UIImageView alloc] init];
    homeicon.image = [UIImage imageNamed:@"homeLeftTopImage"];
    homeicon.size = CGSizeMake(80.0f, 80.0);
    homeicon.center = CGPointMake(60.0f, leftTopView.height / 2.0 + 10.0f);
    [leftTopView addSubview:homeicon];
    
//    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(homeicon.x + 40.0, homeicon.y, 100, homeicon.height)];
//    label.text = @"首页";
//    label.textColor = BPGlobaThemeColor;
//    [leftTopView addSubview:label];
//    UITapGestureRecognizer *backHome = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissMenu)];
//    [leftTopView addGestureRecognizer:backHome];
    return leftTopView;
}

#pragma mark - 边侧栏消失和出现
//侧边栏消失事件
- (void)dismissMenu
{
    if (_isOpen)
    {
        _isOpen = !_isOpen;
        [self.viewAll removeFromSuperview];
        [self performDismissAnimation];
    }
}
//侧边栏显示事件
- (void)showMenu
{
    if (!_isOpen)
    {
        _isOpen = !_isOpen;
        self.viewAll = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - self.leftSideView.frame.size.width + 120, 0, self.view.frame.size.width - self.leftSideView.frame.size.width, self.view.frame.size.height)];
        self.viewAll.backgroundColor = [UIColor clearColor];
        
        UITapGestureRecognizer *tapViewAll = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(disMis)];
        [self.viewAll addGestureRecognizer:tapViewAll];
        
        [self.view addSubview:self.viewAll];
        [self performSelectorInBackground:@selector(performOpenAnimation) withObject:nil];
    }
}

- (void)disMis{
    [self dismissMenu];
}


#pragma - mark 边侧栏动画效果
- (void)dismissMenuWithSelection:(UIButton*)button
{
    [UIView animateWithDuration:0.3f
                          delay:0.0f
         usingSpringWithDamping:.2f
          initialSpringVelocity:10.f
                        options:0 animations:^{
                            button.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.2, 1.2);
                        }
                     completion:^(BOOL finished) {
                         [self dismissMenu];
                     }];
}
//侧边栏消失的动画
- (void)performDismissAnimation
{
    [UIView animateWithDuration:0.4 animations:^{
        _sideNavButton.alpha = 1.0f;
        _sideNavButton.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 0);
        self.leftSideView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, 0);
        
    }];
}
//侧边栏出现的动画
- (void)performOpenAnimation
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.4 animations:^{
            _sideNavButton.alpha = 0.0f;
            _sideNavButton.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 220, 0);
            self.leftSideView.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 220, 0);
        }];
    });
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_btnDataArry count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    homeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_homeID forIndexPath:indexPath];
    HomeModel *info = _btnDataArry[indexPath.row];
    [BPImageTool setUpUIImageView:cell.listImageView addNsstringUrl:info.icon];
    cell.listPrompt.text = info.title;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HomeModel *model = _btnDataArry[indexPath.row];
    BPProductModeViewController *ProductModel = [[BPProductModeViewController alloc] init];
    ProductModel.urlID = model.iD;
    ProductModel.VCtitle = model.title;
    [self.navigationController pushViewController:ProductModel animated:YES];
}

//设置cell的宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat cellW = (BPScreenW - 10) / 2.0;
    CGFloat cellH = cellW - 60.0;
    return CGSizeMake(cellW, cellH);
}

//左右两个cell的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}
//上下两个cell的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

// 整个collectionview离边界的大小
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(_headView.height, 0, 0, 0);
}

//这个方法使用来判断账号有没有登录的，在没有登录的情况下，先登录再进入点击的页面（这是进入原生页面）
- (void)chooseLoginViewController:(NSString *)view title:(NSString *)title
{
    if ([AccountTool account].uid == nil) {
        BPLoginViewController *login = [[BPLoginViewController alloc] init];
        login.isHome = YES;
        [self.navigationController pushViewController:login animated:YES];
        login.block = ^(){
            Class vcName = NSClassFromString(view);
            UIViewController *viewController = [[vcName alloc] init];
            viewController.title = title;
            [self.navigationController pushViewController:viewController animated:YES];
        };
    }else{
        Class vcName = NSClassFromString(view);
        UIViewController *viewController = [[vcName alloc] init];
        viewController.title = title;
        [self.navigationController pushViewController:viewController animated:YES];
    }
}
//这个方法使用来判断账号有没有登录的，在没有登录的情况下，先登录再进入点击的页面（这是进入网页与原生交互的页面）
- (void)chooseLoginWebController:(NSString *)view title:(NSString *)title withWebName:(NSString *)webName
{
    if ([AccountTool account].uid == nil) {
        BPLoginViewController *login = [[BPLoginViewController alloc] init];
        login.isHome = YES;
        [self.navigationController pushViewController:login animated:YES];
        login.block = ^(){
            Class vcName = NSClassFromString(view);
            BaseWebViewController *viewController = [[vcName alloc] init];
            viewController.title = title;
            viewController.webName = webName;
            [self.navigationController pushViewController:viewController animated:YES];
        };
    }else{
        Class vcName = NSClassFromString(view);
        BaseWebViewController *viewController = [[vcName alloc] init];
        viewController.title = title;
        viewController.webName = webName;
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
